use std::io;

fn main() {
    println!("Hello, world!");

    use_loop();

    use_while();

    use_for();

    let mut index = String::new();
    println!("Please input a number: ");
    io::stdin().read_line(&mut index)
               .expect("Failed to read line");
    let index: usize = index.trim().parse().expect("Not a number");
    let value = fibonacci(index);
    println!("{index}: {value}");
}


fn use_loop() {
    println!("use_loop");

    let mut i = 1;
    loop {
        let mut j = 1;
        
        loop {
            print!("{} x {} = {:<3}", j, i, i * j); // {:<3} 表示左对齐，占3个字符宽度
            if j == i {
                break;
            }
            j += 1;
        }

        println!("");

        if i == 9 {
            break;
        }

        i += 1;
    }
}

fn use_while() {
    println!("use_while");

    let mut i = 1;
    while i < 10 {
        let mut j = 1;

        while j <= i {
            print!("{} x {} = {:<3}", j, i, i * j); // {:<3} 表示左对齐，占3个字符宽度
            j += 1;
        }

        println!("");

        i += 1;
    }
}

fn use_for() {
    println!("use_for");

    for i in 1..=9 {
        for j in 1..=i { 
            print!("{} x {} = {:<3}", j, i, i * j); // {:<3} 表示左对齐，占3个字符宽度
        }
        println!("");
    }
}

fn fibonacci(n: usize) -> u32 {
    if n == 0 || n == 1 {
        return n as u32;
    }

    let mut f0: u32 = 0;
    let mut f1: u32 = 1;

    let mut temp: u32;
    for _i in 1..n {
        temp = f1;
        f1 = f0 + f1;
        f0 = temp;
        //println!("f0: {f0}, f1: {f1}")
    }

    return f1;
}
